//
//  SEGWangLongTKManager.m
//  SEGUhomeIntelligentHardware
//
//  Created by Chiang on 2018/5/2.
//  Copyright © 2018年 刘山. All rights reserved.
//

#import "SEGWangLongTKManager.h"
#import "OpenObject.h"
#import <CoreBluetooth/CoreBluetooth.h>

@interface SEGWangLongTKManager ()<RHOpenObjectDelegate>

/// 电梯唯一码数组
@property (nonatomic, strong) NSArray *elevatorArray;
/// 呼梯楼层数组
@property (nonatomic, strong) NSArray *floorNums;
/// 用户ID，八位，不足八位前面补零
@property (nonatomic, copy) NSString *userId;
/// 用户密钥
@property (nonatomic, copy) NSString *keyU;
/// 搜索到的设备唯一码
@property (nonatomic, copy) NSString *devUnique;
/// 回调
@property (nonatomic, copy) SEGOpenElevatorManagerCallBack callBack;

@end

@implementation SEGWangLongTKManager
 
- (void)callElevatorWith:(NSArray *)elevatorArray userId:(NSString *)userId keyU:(NSString *)keyU floorNums:(NSArray *)floorNums callBack:(SEGOpenElevatorManagerCallBack)callback {
    _elevatorArray = elevatorArray;
    _userId = userId;
    _keyU = keyU;
    _floorNums = floorNums;
    _devUnique = nil;
    self.callBack = callback;
    
    // 呼梯初始化和扫描设备
    [self startScanning];
}
- (void)startScanning {
    [OpenObject sharedopenobject].rhOpenobjectDelegate = self;
    // 扫描电梯设备
    [[OpenObject sharedopenobject] scan:self.elevatorArray scanDuration:2 adjustableValue:0];
    // 6秒后如果还没有扫描到设备，停止搜索，返回搜索失败
    [self performSelector:@selector(scanOvertimeAction) withObject:nil afterDelay:6];
}
#pragma mark - RHOpenObjectDelegate
/// 发现设备回调
- (void)didDiscoverPeripheral:(NSDictionary *)peripheralDic {
    for (int i = 0; i < _elevatorArray.count; i++) {
        NSMutableDictionary *dic = [_elevatorArray[i] mutableCopy];
        NSString *discoveredDevUnique = [peripheralDic objectForKey:@"devUnique"];
        if ([[dic objectForKey:@"devUnique"] isEqualToString:discoveredDevUnique]) { // 比对设备唯一吗，找到电梯组里面的含有的
            _devUnique = discoveredDevUnique;
            break;
        }
    }
    if (_devUnique.length > 0) {
        // 找到设备后发起呼梯操作
        [[OpenObject sharedopenobject] openTheDoor:_devUnique keyU:_keyU userId:_userId cmdType:@"2" floorNums:_floorNums];
    } else { // 没有找到设备
        if (self.callBack) self.callBack(SEGOpenDoorStatus_Failed, nil);
    }
}
/// 呼梯结果回调
- (void)resultOpenPeripheral:(NSDictionary *)openPeripheral {
    // 停止扫描
    [[OpenObject sharedopenobject] stopScan];
    if (self.callBack) self.callBack(SEGOpenDoorStatus_Success, openPeripheral);
}
 /// 扫描超时回调
- (void)scanOvertimeAction {
    if(!_devUnique) {
        // 停止扫描
        [[OpenObject sharedopenobject] stopScan];
        if (self.callBack) self.callBack(SEGOpenDoorStatus_Failed, nil);
    }
}

#pragma mark - data deal methods
/**
 把数据转化为16进制数组
 
 @param selefloor 选择的楼层 最多支持2个
 @param floors 有权限的楼层  最多支持112个 区分正背门
 @return 根据有权限的楼层 和 你选择的楼层生产传送给设备的数组
 */
- (NSArray *)getfloorswith:(NSArray *)selefloor and:(NSArray *)floors
{
    NSMutableArray *arr = [[NSMutableArray alloc]init];
    NSMutableArray *a = [[NSMutableArray alloc]init];
    a = [selefloor mutableCopy];
    if (a.count == 1) {
        [a addObject:@[@"0",@"0"]];
    }
    if (a.count == 0) {
        [a addObject:@[@"0",@"0"]];
        [a addObject:@[@"0",@"0"]];
    }
    //添加选中的楼层
    for (int i = 0; i < 2; i++) {
        NSMutableArray *arrs = [a[i] mutableCopy];
        int j = [arrs[0] intValue];
        //            NSString *j = a[i];
        if (j !=0) {
            SEGLog(@"%02x",j);
            NSString *two = [self getBinaryByhex:[[NSString stringWithFormat:@"%02x",j] uppercaseString]];//16进制转2进制
            NSString *two1 = @"";
            //                    NSMutableArray *floors = [d[@"floorNums"] mutableCopy];
            if (j <= 56) {//如果楼层小于56楼 修改二进制字符串的第一个字符为正背门对应的字符
                for (int s = 0; s<floors.count; s++) {
                    NSMutableArray *selefloor = [floors[s] mutableCopy];
                    if ([arrs[0] isEqualToString:selefloor[0]]) {
                        two1 = [two stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:arrs[1]];//正背门替换
                    }
                }
            }
            else{//如果楼层大于56楼 没有背门
                two1 = [two stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:@"0"];
            }
            
            NSString *valueF = [NSString stringWithFormat:@"0x%@",[self getBinaryBytwo:two1]];//2进制转16进制
            [arr addObject:valueF];
        }
        else{
            NSString *valueF = @"0x00";
            [arr addObject:valueF];
        }
    }
    //添加楼层个数
    NSInteger fc = floors.count;
    NSString *valueFc = [NSString stringWithFormat:@"0x%02lx",(long)fc];
    [arr addObject:valueFc];
    //添加各个楼层的信息
    for (int i = 0; i < floors.count; i++) {
        NSMutableArray *arrs = [floors[i] mutableCopy];
        int j = [arrs[0] intValue];
        if (j !=0) {
            SEGLog(@"%02x",j);
            NSString *two = [self getBinaryByhex:[[NSString stringWithFormat:@"%02x",j] uppercaseString]];//16进制转2进制
            NSString *two1 = @"";
            if (j <= 56) {//如果楼层小于56楼 修改二进制字符串的第一个字符为正背门对应的字符
                two1 = [two stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:arrs[1]];//正背门替换
            }
            else{//如果楼层大于56楼 没有背门
                two1 = [two stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:@"0"];
            }
            
            NSString *valueF = [NSString stringWithFormat:@"0x%@",[self getBinaryBytwo:two1]];//2进制转16进制
            [arr addObject:valueF];
        }
        else{
            NSString *valueF = @"0x00";
            [arr addObject:valueF];
        }
    }
    
    return arr;
}
-(NSString *)getBinaryByhex:(NSString *)hex
{
    NSMutableDictionary  *hexDic = [[NSMutableDictionary alloc] init];
    
    hexDic = [[NSMutableDictionary alloc] initWithCapacity:16];
    
    [hexDic setObject:@"0000" forKey:@"0"];
    
    [hexDic setObject:@"0001" forKey:@"1"];
    
    [hexDic setObject:@"0010" forKey:@"2"];
    
    [hexDic setObject:@"0011" forKey:@"3"];
    
    [hexDic setObject:@"0100" forKey:@"4"];
    
    [hexDic setObject:@"0101" forKey:@"5"];
    
    [hexDic setObject:@"0110" forKey:@"6"];
    
    [hexDic setObject:@"0111" forKey:@"7"];
    
    [hexDic setObject:@"1000" forKey:@"8"];
    
    [hexDic setObject:@"1001" forKey:@"9"];
    
    [hexDic setObject:@"1010" forKey:@"A"];
    
    [hexDic setObject:@"1011" forKey:@"B"];
    
    [hexDic setObject:@"1100" forKey:@"C"];
    
    [hexDic setObject:@"1101" forKey:@"D"];
    
    [hexDic setObject:@"1110" forKey:@"E"];
    
    [hexDic setObject:@"1111" forKey:@"F"];
    
    NSString *binaryString= [[NSString alloc] init];
    
    for (int i=0; i<[hex length]; i++) {
        
        NSRange rage;
        
        rage.length = 1;
        
        rage.location = i;
        
        NSString *key = [hex substringWithRange:rage];
        
        binaryString = [NSString stringWithFormat:@"%@%@",binaryString,[NSString stringWithFormat:@"%@",[hexDic objectForKey:key]]];
    }
    
    return binaryString;
    
}
//二进制转十六进制
- (NSString *)getBinaryBytwo:(NSString *)two
{
    NSMutableDictionary  *hexDic = [[NSMutableDictionary alloc] init];
    
    hexDic = [[NSMutableDictionary alloc] initWithCapacity:16];
    
    [hexDic setObject:@"0" forKey:@"0000"];
    
    [hexDic setObject:@"1" forKey:@"0001"];
    
    [hexDic setObject:@"2" forKey:@"0010"];
    
    [hexDic setObject:@"3" forKey:@"0011"];
    
    [hexDic setObject:@"4" forKey:@"0100"];
    
    [hexDic setObject:@"5" forKey:@"0101"];
    
    [hexDic setObject:@"6" forKey:@"0110"];
    
    [hexDic setObject:@"7" forKey:@"0111"];
    
    [hexDic setObject:@"8" forKey:@"1000"];
    
    [hexDic setObject:@"9" forKey:@"1001"];
    
    [hexDic setObject:@"A" forKey:@"1010"];
    
    [hexDic setObject:@"B" forKey:@"1011"];
    
    [hexDic setObject:@"C" forKey:@"1100"];
    
    [hexDic setObject:@"D" forKey:@"1101"];
    
    [hexDic setObject:@"E" forKey:@"1110"];
    
    [hexDic setObject:@"F" forKey:@"1111"];
    
    NSString *binaryString = [[NSString alloc] init];
    
    for (int i=0; i<[two length]/4; i++) {
        
        NSRange rage;
        
        rage.length = 4;
        
        rage.location = i*4;
        
        NSString *key = [two substringWithRange:rage];
        
        binaryString = [NSString stringWithFormat:@"%@%@",binaryString,[NSString stringWithFormat:@"%@",[hexDic objectForKey:key]]];
    }
    
    return binaryString;
}
@end
